var item = {};
document.addEventListener('DOMContentLoaded', function() {
	chrome.storage.sync.get("osc_oscer_block", function(itemx) {
		if(typeof(itemx.osc_oscer_block) != 'undefined') {
			item = itemx;
			//log("osc_oscer_block:"+item.osc_oscer_block);
		
			var template = $('#template');
			var temp = template.clone(true).attr('id', '').show();
		
			var arr = item.osc_oscer_block.split(";");
			for(i in arr) {
				var val = arr[i];
				if(val == "") continue;
				//log(val);
				
                // url
                var regx = new RegExp('#url', 'g');
                var html = temp.html().replace(regx, val || '');
			
				// name
				//var tempArr = val.split("/");                //
                //regx = new RegExp('#name', 'g');
                //html = html.replace(regx, tempArr[tempArr.length-1] || '');
				
                // display:none;
                var regx = new RegExp('display:none;', 'g');
                html = html.replace(regx, '');
				
            	template.parent().append(html);
			}
			
		  	$('.del_btn').click(function() {
		  		var url = $(this).attr('title'), temp="";

				var arr = item.osc_oscer_block.split(";");
				for(i in arr) {
					var val = arr[i];
					if(val == url) continue;
		
					temp = temp + ";" + val;
				}

				var json = {"osc_oscer_block": temp};
				chrome.storage.sync.set(json, function() {
					window.location.reload();
				});
		  	});
		} else {
			item = {"osc_oscer_block": ""};
		}
	}); // #END chrome.storage.sync.get
	
	// listener
  	document.querySelector('#add_btn').addEventListener('click', function() {
  		var url = document.querySelector('#add_text').value;
		if(url == "") return;
		if(url.indexOf('atearsan') > 0) {
			log('不要调皮, 怎么能屏蔽我!');
			return;
		}
		
		var json = {"osc_oscer_block": url + ';' + item.osc_oscer_block.replace(/;+/g, ";")};
		chrome.storage.sync.set(json, function() {
			window.location.reload();
		});
  	});
  	document.querySelector('#help').addEventListener('click', function() {
		var display = $('#help_img').css('display');
		if(display == 'none') {
	  		$('#help_img').slideDown();
		} else {
	  		$('#help_img').slideUp();
		}
  	});
  	document.querySelector('#help_img').addEventListener('click', function() {
  		$('#help_img').slideUp();
  	});
});

function log(str) {
	var x = document.getElementById('temp').innerText;
	document.getElementById('temp').innerText = str + '\r\n' + x;
}